using MediatR;
using Medical.Domain;
using Medical.Infrastructrue.Interfaces;
using Medical.WriteApi.Appcontext.Command;

namespace Medical.WriteApi.Appcontext.CommandHandler
{
	/// <summary>
	/// 删除挂号单模板命令处理器（逻辑删除）
	/// </summary>
	public class DeleteRegistrationSlipTemplateCommandHandler : IRequestHandler<DeleteRegistrationSlipTemplateCommand, bool>
	{
		private readonly IBaseRepository<RegistrationSlipTemplate> _repository;

		public DeleteRegistrationSlipTemplateCommandHandler(IBaseRepository<RegistrationSlipTemplate> repository)
		{
			_repository = repository;
		}

		public async Task<bool> Handle(DeleteRegistrationSlipTemplateCommand request, CancellationToken cancellationToken)
		{
			var entity = await _repository.GetModel(x => x.TemplateId == request.TemplateId && !x.IsDeleted);
			
			if (entity == null)
			{
				throw new Exception("模板不存在");
			}

			// 逻辑删除
			entity.IsDeleted = true;
			entity.DeletedAt = DateTime.Now;
			entity.DeletedBy = request.DeletedBy;
			entity.UpdatedAt = DateTime.Now;

			await _repository.UpdateAsync(entity);

			return true;
		}
	}
}
